<template>
    <div class="upload-container">
      <el-card>
        <template #header>
          <span>图片上传</span>
        </template>
  
        <!-- 上传组件 -->
        <el-upload
          class="upload-demo"
          action="http://localhost:9090/api/upload/image"
          :show-file-list="true"
          :on-success="handleSuccess"
          :on-error="handleError"
          :before-upload="beforeUpload"
          list-type="picture"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-card>
  
      <!-- 显示上传成功的图片 -->
      <div v-if="uploadedImage" class="image-preview">
        <el-divider>上传成功的图片</el-divider>
        <el-image :src="uploadedImage" fit="contain" />
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref } from "vue";
  import { ElMessage } from "element-plus";
  
  const uploadedImage = ref(""); // 存储上传成功后的图片地址
  
  // 上传前检查文件格式和大小
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith("image/");
    const isLt2M = file.size / 1024 / 1024 < 2; // 限制 2MB
  
    if (!isImage) {
      ElMessage.error("只能上传图片文件！");
      return false;
    }
    if (!isLt2M) {
      ElMessage.error("图片大小不能超过 2MB！");
      return false;
    }
  
    return true;
  };
  
  // 处理上传成功
  const handleSuccess = (response) => {
    ElMessage.success("上传成功！");
    uploadedImage.value = `http://localhost:9090/uploads/${response.data.filename}`;
  };
  
  // 处理上传失败
  const handleError = (error) => {
    console.error("上传失败:", error);
    ElMessage.error("上传失败，请重试！");
  };
  </script>
  
  <style scoped>
  .upload-container {
    width: 400px;
    margin: 50px auto;
    text-align: center;
  }
  
  .image-preview {
    margin-top: 20px;
  }
  </style>
  